<template>
  <div v-loading="loading">
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="coalType">
        <el-select
          multiple
          clearable
          v-model="queryParams.coalType"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in coalTypeList"
            :key="dict.id"
            :label="dict.coalName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标段大小" prop="sectionSize">
        <el-select
          multiple
          clearable
          v-model="queryParams.sectionSize"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_SECTION_SIZE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易方式" prop="tradingWay">
        <el-select clearable v-model="queryParams.tradingWay" placeholder="请选择" class="!w-300px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_TRADING_WAY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button-group class="ml-4">
          <el-button
            v-for="item in dateTypeList"
            :type="queryParams.timePeriod === item.value ? 'primary' : 'default'"
            @click="dateTypeChange(item.value)"
            :key="item.value"
            >{{ item.label }}</el-button
          >
        </el-button-group>
      </el-form-item>
      <el-form-item label="选择时间" prop="tradingDate">
        <DatePicker
          v-model="queryParams.tradingDate"
          :dateType="queryParams.timePeriod"
          @dataChange="datePickerChange"
        >
        </DatePicker>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-card class="mt-20px chart-card">
      <el-button-group>
        <el-button
          v-for="item in getIntDictOptions(DICT_TYPE.BID_SECTION_STATISTIC_TYPE)"
          :type="chartType === item.value ? 'primary' : 'default'"
          @click="sectionStatisticTypeChange(item)"
          :key="item.value"
          >{{ item.label }}</el-button
        >
      </el-button-group>
      <section class="flex space-x-12 mt-20px">
        <div class="h-300px w-1/3">
          <Echart :options="pieOptionData" :height="300" @initReady="initPie" />
        </div>
        <div class="h-300px w-2/3">
          <Echart :options="barsOptionData" :height="300" @initReady="initBars" />
        </div>
      </section>
    </el-card>
    <el-card class="mt-20px">
      <!-- 列表 -->
      <el-table
        :data="list"
        border
        stripe
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
      >
        <el-table-column label="编号" align="center" width="60" fixed="left">
          <template #default="{ $index, row }">
            {{ row.statisticField !== '合计' ? $index + 1 : '' }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="chartType === 1"
          label="产品名称"
          align="center"
          prop="statisticField"
          min-width="150"
          fixed="left"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          v-if="chartType === 2"
          label="标段大小"
          align="center"
          prop="statisticField"
          min-width="150"
          fixed="left"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{
              row.statisticField === '合计'
                ? row.statisticField
                : getDictLabel(DICT_TYPE.BID_SECTION_SIZE, row?.statisticField?.toString())
            }}
          </template>
        </el-table-column>

        <el-table-column
          v-if="chartType === 3"
          label="标段状态"
          align="center"
          prop="statisticField"
          min-width="150"
          fixed="left"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{
              row.statisticField === '合计'
                ? row.statisticField
                : getDictLabel(DICT_TYPE.BID_TRADING_WAY, row?.statisticField?.toString())
            }}
          </template>
        </el-table-column>
        <el-table-column label="销量合计(万吨)" align="center" prop="salesTotal" min-width="150" />
        <el-table-column
          label="销售金额合计(万元)"
          align="center"
          prop="salesMoneyTotal"
          min-width="150"
        />
        <el-table-column
          label="平均起拍价(元/吨)"
          align="center"
          prop="avgStartingPrice"
          min-width="150"
        />
        <el-table-column label="平均价格(元/吨)" align="center" prop="avgPrice" min-width="150" />
        <el-table-column label="平均溢价(元/吨)" align="center" prop="avgPremium" min-width="150" />
      </el-table>
    </el-card>
  </div>
</template>
<script setup lang="ts" name="sectionAnalysis">
import * as Utils from '@/utils/dict'
import * as dataCenter from '@/api/dataCenter'
import { EChartsOption } from 'echarts'
import { pieOption, barsOption } from '../echarts-data'
import { cloneDeep } from 'lodash-es'
import { formatDate } from '@/utils/formatTime'
import { dateTypeList } from '../dataCenter.data'
import { initMonthTimeRange, isHasData } from '@/utils/common'

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const queryFormRef = ref()
const chartType = ref(1)
const message = useMessage()
const coalTypeList: Record<string, any> = ref([])
const pieOptionData = reactive<EChartsOption>(pieOption) as EChartsOption
const barsOptionData = reactive<EChartsOption>(barsOption) as EChartsOption
const queryParams: Record<string, any> = ref({
  coalType: [],
  sectionSize: [],
  tradingWay: undefined,
  timePeriod: 'month',
  tradingDate: []
})

const colorList = [
  '#2EB7D4',
  '#3AB177',
  '#FBB437',
  '#fca5a5',
  '#fcd34d',
  '#f59e0b',
  '#b45309',
  '#fdba74',
  '#f97316',
  '#c2410c',
  '#ef4444',
  '#b91c1c',
  '#f9a8d4',
  '#ec4899',
  '#be185d',
  '#bef264',
  '#84cc16',
  '#4d7c0f',
  '#6ee7b7',
  '#10b981',
  '#047857',
  '#98429B',
  '#67e8f9',
  '#06b6d4',
  '#0e7490',
  '#c4b5fd',
  '#8b5cf6',
  '#6d28d9',
  '#f0abfc',
  '#d946ef',
  '#a21caf',
  '#ffe4e6',
  '#ffedd5',
  '#fef3c7',
  '#d1fae5',
  '#ccfbf1',
  '#e0f2fe',
  '#e0e7ff',
  '#ede9fe',
  '#fae8ff',
  '#831843',
  '#7c2d12',
  '#365314',
  '#064e3b',
  '#164e63',
  '#1e3a8a',
  '#4c1d95',
  '#701a75',
  '#dde1e3',
  '#cbd5e1'
]

const chartFieldMap = {
  1: 'coalTypeMap',
  2: 'sectionSizeMap',
  3: 'tradingWayMap'
}
const { DICT_TYPE, getIntDictOptions, getStrDictOptions, getDictLabel } = reactive(Utils)

const chartFieldObj = {
  coalTypeMap: getStrDictOptions(DICT_TYPE.BID_COAL_TYPE).reduce(
    (obj, item: Record<string, any>) => ({ ...obj, [item.value]: item.label }),
    {}
  ),
  sectionSizeMap: getStrDictOptions(DICT_TYPE.BID_SECTION_SIZE).reduce(
    (obj, item: Record<string, any>) => ({ ...obj, [item.value]: item.label }),
    {}
  ),
  tradingWayMap: getStrDictOptions(DICT_TYPE.BID_TRADING_WAY).reduce(
    (obj, item: Record<string, any>) => ({ ...obj, [item.value]: item.label }),
    {}
  )
}

let pieChart: any = null
let barChart: any = null
let timeTange: any[] = []

/** 查询列表 */

const getList = async () => {
  loading.value = true
  try {
    getSectionStatisticsChart()
    getSectionStatistics()
  } finally {
    loading.value = false
  }
}

const getBody = () => {
  const params = cloneDeep(queryParams.value)
  if (!params?.sectionSize?.length) {
    delete params.sectionSize
  }
  if (!params?.tradingWay) {
    delete params.tradingWay
  }
  if (params?.coalType?.length) {
    params.coalId = params.coalType.join(',')
  }
  if (params?.sectionSize?.length) {
    params.sectionSize = params.sectionSize.join(',')
  }
  if (timeTange.length > 1) {
    params.tradingDate = timeTange
  }
  params['staticsType'] = chartType.value
  delete params.coalType
  return params
}

const getSectionStatisticsChart = async () => {
  const res = await dataCenter.getSectionStatisticsChart(getBody())
  const pieChartMap = res?.pieChartMap
  const columnChart = res?.columnChart
  initPieData(pieChartMap)
  initBarsData(columnChart)
}

const getSectionStatistics = async () => {
  list.value = await dataCenter.getSectionStatistics(getBody())
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (timeTange.length !== 2) {
    message.warning('选择时间不能为空')
    return
  }
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.value.timePeriod = 'month'
  timeTange = initMonthTimeRange()
  nextTick(() => {
    queryParams.value.tradingDate = formatDate(new Date(), 'YYYY-MM-DD')
  })
  handleQuery()
}

const dateTypeChange = (type) => {
  timeTange = []
  queryParams.value.timePeriod = type
  if (type === 'daterange') {
    queryParams.value.tradingDate = []
  } else {
    queryParams.value.tradingDate = undefined
  }
}

const datePickerChange = ($event) => {
  timeTange = $event
}

const sectionStatisticTypeChange = (item) => {
  if (timeTange.length !== 2) {
    message.warning('选择时间不能为空')
    return
  }
  chartType.value = item.value
  pieChart?.clear()
  barChart?.clear()
  getList()
}

const initPie = (chart) => {
  pieChart = chart
  pieChart?.on('legendselectchanged', (event: Record<string, any>) => {
    barChart?.setOption({
      legend: {
        selected: event.selected
      }
    })
  })
}

const initBars = (chart) => {
  barChart = chart
}

const initPieData = (data) => {
  pieChart.setOption({
    color: colorList,
    tooltip: {
      trigger: 'item',
      formatter: '{b} : {c}万吨'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: getPieLegendData(data)
    },
    series: [
      {
        type: 'pie',
        radius: '55%',
        center: ['62%', '60%'],
        data: getPieSeriesData(data),
        labelLine: {
          length: 10,
          length2: 10
        }
      }
    ]
  })
}

const getPieLegendData = (data) => {
  if (isHasData(data)) {
    return []
  }
  const result = Object.keys(data).sort()
  return chartType.value === 1
    ? result
    : result.map((key) => chartFieldObj[chartFieldMap[chartType.value]][key])
}

const getPieSeriesData = (data) => {
  if (isHasData(data)) {
    return []
  }
  return Object.keys(data)
    .sort()
    .map((key) => {
      return {
        name: chartType.value === 1 ? key : chartFieldObj[chartFieldMap[chartType.value]][key],
        value: data[key]
      }
    })
}

const initBarsData = (data) => {
  barChart.setOption({
    color: colorList,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      show: false
    },
    grid: {
      top: 30,
      left: 80,
      right: 80,
      bottom: 30
    },
    xAxis: {
      data: getBarsLegendData(data)
    },
    yAxis: [
      {
        type: 'value',
        name: '单位：万吨',
        nameTextStyle: {
          align: 'right'
        }
      },
      {
        type: 'value',
        name: '单位：万元',
        nameTextStyle: {
          align: 'left'
        }
      }
    ],
    series: getBarsSeriesData(data),
    dataZoom: [
      {
        type: 'slider',
        left: 75,
        start: 50,
        end: 100,
        height: 16,
        bottom: 40,
        handleSize: '100%',
        moveHandleSize: 14
      }
    ]
  })
}

const getBarsLegendData = (data) => {
  if (isHasData(data?.date)) {
    return []
  }
  return data?.date
}

const getBarsSeriesData = (data) => {
  if (isHasData(data.columnChartMap)) {
    return []
  }
  const dataList = Object.keys(data.columnChartMap)
    .sort()
    .map((key) => {
      return {
        name:
          chartType.value === 1 || key === '销售金额合计'
            ? key
            : chartFieldObj[chartFieldMap[chartType.value]][key],
        data: data.columnChartMap[key],
        type: 'bar',
        yAxisIndex: key === '销售金额合计' ? 1 : 0,
        tooltip: {
          valueFormatter: (value) => {
            return `${value}${key === '销售金额合计' ? '万元' : '万吨'}`
          }
        }
      }
    })
  return dataList
}

const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

/** 初始化 **/
onMounted(() => {
  queryParams.value.tradingDate = formatDate(new Date(), 'YYYY-MM-DD')
  timeTange = initMonthTimeRange()
  bidCoalManageList()
  getList()
})
</script>
<style lang="scss" scoped>
:deep(.chart-card.el-card) {
  overflow: inherit !important;
}
</style>
